<!--奖金池管理-->
<template>
  <basic-container class="bonus">
    <!--搜索栏目-->
    <div class="search-form flex-l-r">
        <div class="flex">
          <el-form :inline="true" :model="searchForm" >
            <el-form-item label="负责机构">
              <el-select v-model="searchForm.deptId" placeholder="负责机构" @change="changeDept">
                <el-option
                  v-for="item in bonusItemDeptIdOptions"
                  :key="item.deptId"
                  :label="item.name"
                  :value="item.deptId">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="年度">
              <el-date-picker
                v-model="searchForm.year"
                type="year"
                :clearable="false"
                value-format="yyyy"
                @change="changYear"
                placeholder="选择年">
              </el-date-picker>
            </el-form-item>
          </el-form>
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </div>
        <div>
          <el-radio-group v-model="searchForm.timeType" size="small" @change="changeType">
            <el-radio-button label="month">年度</el-radio-button>
            <el-radio-button label="quarter">季度</el-radio-button>
          </el-radio-group>
        </div>
    </div>
    <div class="table-tile">
      <span>{{searchForm.year}}年奖金池明细（暂缓发放）</span>
    </div>
    <el-form :model="formData">
       <el-table ref="leaveTableRef" :data="formData.leaveTable" v-loading="loading" border
              class="edit-table count"
              show-summary
              :cell-class-name="lastColClass"
              :summary-method="getSummaries"
              :height="`calc(100vh - 630px )`">
      <el-table-column
        width="60px"
        prop=""
        label="序号"
        align="center"
      >
        <template slot-scope="scope">
          <span>{{scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="bonusItemName"
        label="考核项"
        align="left"
        min-width="140"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        v-for="item in columns"
        :prop="item.prop"
        :label="item.label"
        align="center"
        header-align="center"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
           <el-form-item :prop="`leaveTable.${scope.$index}.${item.prop}`" >
<!--             :rules="[{validator:$validateUtil.dynamic,prop:item.prop,label:item.label,row:scope.row,ruleType:'',trigger: 'change' }]"-->
              <el-input-number v-if="searchForm.timeType == 'month'" class="w100" placeholder="请输入"
                               :controls="false"
                               v-model.trim="scope.row[item.prop]"
                               @change="saveCell(scope.row,item.prop,`${scope.$index}`,'1')" ></el-input-number>
              <span v-else>{{scope.row[item.prop]}}</span>
           </el-form-item>
        </template>
      </el-table-column>
      <el-table-column
        prop="totle"
        label="合计"
        show-overflow-tooltip
        align="center" header-align="center"
      >
        <template slot-scope="scope">
          <span>{{sumCols(scope.row)}}</span>
        </template>
      </el-table-column>
    </el-table>
    </el-form>


    <div class="table-tile mg-t20">
      <span>{{searchForm.year}}年奖金池明细（发放明细）</span>
    </div>
    <el-form :model="formData">
      <el-table ref="sendTableRef" class="edit-table count" :data="formData.sendTable" v-loading="loading" border
                show-summary
                :cell-class-name="lastColClass"
                :summary-method="getSummaries"
                :height="`calc(100vh - 630px )`">
        <el-table-column
          width="60px"
          prop=""
          label="序号"
          align="center"
        >
          <template slot-scope="scope">
            <span>{{scope.$index + 1}}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="bonusItemName"
          label="考核项"
          min-width="140"
          align="left"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          v-for="item in columns"
          :prop="item.prop"
          :label="item.label"
          align="center"
          header-align="center"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <el-form-item :prop="`sendTable.${scope.$index}.${item.prop}`" >
<!--              :rules="[{validator:$validateUtil.dynamic,prop:item.prop,label:item.label,row:scope.row,ruleType:'',trigger: 'change' }]"-->
              <el-input-number v-if="searchForm.timeType == 'month'" class="w100"
                               placeholder="请输入" :controls="false"
                               v-model.trim="scope.row[item.prop]"
                               @change="saveCell(scope.row,item.prop,`${scope.$index}`,'0')"></el-input-number>
              <span v-else>{{scope.row[item.prop]}}</span>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          prop="totle"
          label="合计"
          show-overflow-tooltip
          align="center" header-align="center"
        >
          <template slot-scope="scope">
            <span>{{sumCols(scope.row)}}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-form>

    <el-form :model="formData">
      <el-table ref="poolTableRef"
                class="edit-table count"
                :data="formData.poolTable"
                :show-header="false" border
                :row-class-name="countRowClass">
        <el-table-column
          width="60px"
          prop=""
          label="序号"
          align="center" header-align="center"
        >
          <template slot-scope="scope">
            <span>-</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="bonusItemName"
          label="考核项"
          min-width="140"
          show-overflow-tooltip
          align="left" header-align="left"
        ></el-table-column>
        <el-table-column
          v-for="item in columns"
          :prop="item.prop"
          :label="item.label"
          show-overflow-tooltip
          align="center" header-align="center"
        >
          <template slot-scope="scope">
            <el-form-item :prop="`poolTable.${scope.$index}.${item.prop}`">
              <span>{{scope.row[item.prop]}}</span>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column
          prop="totle"
          label="合计"
          show-overflow-tooltip
          align="center" header-align="center"
        >
        </el-table-column>
      </el-table>
    </el-form>

  </basic-container>
</template>

<script>
import {getOrg, getPoolData,saveCell} from '@/api/bonus/pool'
import moment from "moment";
export default{
  name:"items",
  components:{
  },
  data() {
    return {
      loading:false,
      formData:{
        leaveTable: [],
        sendTable:[],
        poolTable:[],
      },
      searchForm: {deptId:'',timeType:'month',year:moment().format('yyyy')},
      bonusItemDeptIdOptions:[], //机构
      columnsMonth:[
        {
          label:'1月',
          prop:'month1'
        },
        {
          label:'2月',
          prop:'month2'
        },
        {
          label:'3月',
          prop:'month3'
        },
        {
          label:'4月',
          prop:'month4'
        },
        {
          label:'5月',
          prop:'month5'
        },
        {
          label:'6月',
          prop:'month6'
        },
        {
          label:'7月',
          prop:'month7'
        },
        {
          label:'8月',
          prop:'month8'
        },
        {
          label:'9月',
          prop:'month9'
        },
        {
          label:'10月',
          prop:'month10'
        },
        {
          label:'11月',
          prop:'month11'
        },
        {
          label:'12月',
          prop:'month12'
        },
      ],
      columnsQuarter:[
        {
          label:'第一季度',
          prop:'quarter1'
        },
        {
          label:'第二季度',
          prop:'quarter2'
        },
        {
          label:'第三季度',
          prop:'quarter3'
        },
        {
          label:'第四季度',
          prop:'quarter4'
        }
      ],
      columns:[]
    }
  },
  computed: {

  },
  created(){
    //初始化获取二级机构
    this.getOrg() ;
    //根据年度、季度初始化表格列
    this.searchForm.timeType == 'month' ? this.columns = this.columnsMonth : this.columns = this.columnsQuarter
  },
  methods:{
    getOrg(){
      getOrg().then(res => {
        this.bonusItemDeptIdOptions = res.data.data
        this.$set(this.searchForm,'deptId',this.bonusItemDeptIdOptions[0].deptId)
        //获取数据
        this.onLoad() ;
      })
    },
    onLoad(){
      this.onLoadLeaveTable() ;
      this.onLoadSendTable() ;
      this.onLoadPoolTable() ;
    },
    onLoadLeaveTable(){
      this.loading = true ;
      getPoolData(Object.assign(this.searchForm,{poolType:1})).then(res=>{
        if (res.data.code == 0){
          this.formData.leaveTable = res.data.data
          this.oldLeaveTable = JSON.parse(JSON.stringify(this.formData.leaveTable)) ;//单元格编辑失败时，恢复原始值
          this.$nextTick(()=>{
            this.$refs.leaveTableRef.doLayout() ;
          })
        }else{
          this.$message.error(res.data.msg)
        }
        this.loading = false ;
      }).catch(()=>{
        this.loading = false ;
      })
    },
    onLoadSendTable(){
      this.loading = true ;
      getPoolData(Object.assign(this.searchForm,{poolType:0})).then(res=>{
        if (res.data.code == 0){
          this.formData.sendTable = res.data.data
          this.oldSendTable = JSON.parse(JSON.stringify(this.formData.sendTable)) ;//单元格编辑失败时，恢复原始值
          this.$nextTick(()=>{
            this.$refs.sendTableRef.doLayout() ;
          })
        }else{
          this.$message.error(res.data.msg)
        }
        this.loading = false ;
      }).catch(()=>{
        this.loading = false ;
      })
    },
    onLoadPoolTable(){
      this.loading = true ;
      getPoolData(Object.assign(this.searchForm,{poolType:2})).then(res=>{
        if (res.data.code == 0){
          this.formData.poolTable = res.data.data
          this.formData.poolTable[0].bonusItemName = '奖金池剩余金额'
          this.$nextTick(()=>{
            this.$refs.poolTableRef.doLayout() ;
          })
        }else{
          this.$message.error(res.data.msg)
        }
        this.loading = false ;
      }).catch(()=>{
        this.loading = false ;
      })
    },
    handleSearch(){
      this.onLoad() ;
    },
    //切换年度、季度
    changeType(){
      this.searchForm.timeType == 'month' ? this.columns = this.columnsMonth : this.columns = this.columnsQuarter
      this.onLoad() ;
    },
    //切换年
    changYear(){
      this.onLoad() ;
    },
    //切换机构
    changeDept(){
      this.onLoad() ;
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '-';
          return;
        }else if (index === 1){
          sums[index] = '合计';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
        } else {
          sums[index] = 'N/A';
        }
      });

      return sums;
    },
    lastColClass({row, column, rowIndex, columnIndex}){
      if (column.property == 'totle'){
        return 'lastCell'
      }
    },
    countRowClass({row, column, rowIndex, columnIndex}){
      return 'countRow'
    },
    sumCols(row){
      let props = [] ;
      let columns =  [] ;
      this.searchForm.timeType == 'month' ? columns = this.columnsMonth : columns = this.columnsQuarter
      props = columns.map(item=>{
         return item.prop
       })

      let  values = []
      for (let key in row){
        if (props.includes(key)){
          values.push(Number( row[key] ? row[key] : 0))
        }
      }

      let sum = 0
      sum = values.reduce((prev, curr) => {
        const value = Number( curr ? curr : 0);
        if (!isNaN(value)) {
          return Number(prev) + Number(curr);
        } else {
          return Number( prev);
        }
      }, 0);

      return sum
    } ,
    /**
     *
     * @param rowData 点击的单元格所在行的数据
     * @param prop  点击的单元格的属性
     * @param index 点击的单元格的行索引 从 0 开始
     * @param type  1 暂缓发放 0 发放明细
     */
    saveCell(rowData,prop,index,type){
      // let flag = true ;
      // this.$refs.leaveTableRef.validateField(`tableData.${index}.${prop}`,valid => { //被点击的单元格的验证
      //   if (!valid){
      //     flag = true ;
      //   }else{
      //     flag = false ;
      //   }
      // });
      //
      // if (!flag) return

      this.loading = true
      saveCell({id:rowData.id,columnName:prop,columnValue:rowData[prop]}).then(res=>{
        if (res.data.code == 0){
          this.$message.success('修改成功')
          this.onLoadPoolTable() ;
        }else{
          this.$message.error('修改失败')
          if (type == 1){
            this.formData.leaveTable[index][prop] = this.oldLeaveTable[index][prop] //如果保存失败，恢复到初始值
          }else{
            this.formData.sendTable[index][prop] = this.oldSendTable[index][prop] //如果保存失败，恢复到初始值
          }

        }
        this.loading = false
      }).catch(err=>{
        if (type == 1){
          this.formData.leaveTable[index][prop] = this.oldLeaveTable[index][prop] //如果保存失败，恢复到初始值
        }else{
          this.formData.sendTable[index][prop] = this.oldSendTable[index][prop] //如果保存失败，恢复到初始值
        }
        this.loading = false
      })
    },
  }
}
</script>
<style scoped>

</style>
